const mongoose = require('mongoose')
const glob = require('glob')
const path = require('path')
const db_url = 'mongodb://localhost/fireAlarm'
mongoose.Promise = global.Promise
module.exports = {
    initSchema(){
        glob.sync(path.resolve(__dirname,'./schema/','./**/*.js')).forEach(require)
    },
    connectdb(){
        let maxConnection = 0
        mongoose.connect(db_url,{useNewUrlParser:true})
        mongoose.connection.on('disconnectd',()=>{
            maxConnection ++
            if(maxConnection<5){
                mongoose.connect(db_url,{useNewUrlParser:true})
            }else{
                throw new Error('连接超时,请检查数据库')
            }
        })
        mongoose.connection.on('error',()=>{
            maxConnection ++
            if(maxConnection<5){
                mongoose.connect(db_url,{useNewUrlParser:true})
            }else{
                throw new Error('连接超时,请检查数据库')
            }
        })
        mongoose.connection.on('open',()=>{
            console.log('mongodb数据库连接成功')
            // const UserModel = mongoose.model('user')
            // const user = new UserModel({username:'zs',password:'123456',email:'476215526@qq.com'})
            // user.save().then((user)=>{
            //     console.log(user)
            // })
        })
    }
}